package vocabularyhub.word.process.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import org.apache.log4j.Logger;

import vocabularyhub.word.model.IWord;

public class SerializeUtil {

    static Logger logger = Logger.getLogger(SerializeUtil.class);

    @SuppressWarnings("unchecked")
    public static List<IWord> deserialize(File file) {
        List<IWord> wordList = null;
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                    file));
            wordList = (List<IWord>) (in.readObject());
            in.close();
        } catch (Exception x) {
            logger.warn(x.getMessage());
        }
        return wordList;
    }

    public static boolean serialize(File file, List<IWord> list) {

        try {
            logger.trace(String.format("Serializeing %s words to file: %s",
                    list
                    .size(), file.getAbsolutePath()));
            ObjectOutputStream out = new ObjectOutputStream(
                    new FileOutputStream(file));
            out.writeObject(list);
            out.close();
        } catch (Exception x) {
            logger.warn(x.getMessage());
        }

        return true;
    }

    public void quickTest() {
        new SerializeUtil();
        List<IWord> words = SerializeUtil.deserialize(new File(
        "contents\\test.bin"));

        for (IWord word : words) {
            logger.debug(word.toString());
        }

    }

    public static void main(String args[]) {
        new SerializeUtil().quickTest();
    }

    // public List deserialize(File file) {
    // List<?> wordList = null;
    // try {
    //
    // ObjectInputStream in = new ObjectInputStream(new FileInputStream(
    // file));
    //
    // wordList = (List<?>) (in.readObject());
    // in.close();
    // } catch (Exception x) {
    // System.out.println(x.getMessage());
    // }
    // return wordList;
    // }
    //
    // public static void main(String[] args) {
    //
    // }
    //
    // @Override
    // public boolean serialize(File file, List<? extends IWord> list) {
    // try {
    // logger.info(String.format("Serializeing %s to file: %s", list
    // .toString(), file.getAbsolutePath()));
    // ObjectOutputStream out = new ObjectOutputStream(
    // new FileOutputStream(file));
    // out.writeObject(list);
    // out.close();
    // } catch (Exception x) {
    // System.out.println(x.toString());
    // }
    // }

}
